package com.springcloudalibaba.bclass.base;

import com.alibaba.fastjson.JSONObject;
import com.springcloudalibaba.bclass.enums.SysStateEnum;
import com.springcloudalibaba.bclass.util.LoggerUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.MessageFormat;

/**
 * @描述: TODO 请求数据响应工具类，支持范型
 * @作者: lixing lixing_java@163.com
 * @日期 2019/10/10 21:15
 */
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class BaseResult<T> implements Serializable {
    /**
     * @描述 响应编码
     */
    private int code;
    /**
     * @描述 响应描述
     */
    private String msg;
    /**
     * @描述 响应数据类型（范型）
     */
    private T data;

    /**
     * @描述 TODO 成功响应
     */
    public BaseResult<T> success() {
        return success(null);
    }

    /**
     * @描述 TODO 失败响应
     */
    public BaseResult<T> fail() {
        return fail(null);
    }

    /**
     * @描述 TODO 成功响应
     */
    public BaseResult<T> success(T data) {
        this.setCode(SysStateEnum.RESPONSE_STATUS_SUCCESS.getValue());
        this.setMsg("操作成功");
        this.setData(data);
        return this;
    }

    /**
     * @描述 TODO 失败响应
     */
    public BaseResult<T> fail(String msg) {
        this.setCode(SysStateEnum.RESPONSE_STATUS_FALSE.getValue());
        this.setMsg(msg);
        return this;
    }

    /**
     * @描述 TODO 判断当前响应的状态是否成功
     */
    public boolean isSuccess() {
        return this.code == SysStateEnum.RESPONSE_STATUS_SUCCESS.getValue();
    }

    /**
     * @描述 TODO 输出JSON字符串到浏览器
     * @作者 lixing
     * @日期 2019/6/29 22:47
     * @Param [response, responseObject]

     */
    public static void outputJson(HttpServletResponse response, Object responseObject) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = null;
        try {
            String jsonString = JSONObject.toJSONString(responseObject);
            jsonString = jsonString.replace(",\"true\":false", "");
            printWriter = response.getWriter();
            printWriter.write(jsonString);
            printWriter.flush();
        } catch (IOException e) {
            LoggerUtil.error(MessageFormat.format("输出JSON字符串到前台出错: {0}\n", e.getMessage()));
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

}
